<?php
// +----------------------------------------------------------------------
// | KITEGO-Admin「开箱即用」「人人全栈」
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2024 https://www.kitego.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed KITEGO并不是自由软件，未经许可不能去掉KITEGO相关版权
// +----------------------------------------------------------------------
// | Author: KITEGO Team <bd@kitego.cn>
// +----------------------------------------------------------------------

namespace app\adminapi\services\setting;

use app\dao\setting\SystemConfigDao;
use Exception;
use kitego\enums\AmisKeywordsEnum;

class SystemConfigService
{
    private SystemConfigDao $dao;

    public function __construct(SystemConfigDao $dao)
    {
        $this->dao = $dao;
    }

    /**
     * 获取系统非敏感配置项
     */
    public function getSysConfigByGuest()
    {
        $fields = [
            'sys_logo', 'sys_name', 'sys_version', 'sys_slogan', 'sys_describe', 'sys_captcha_type',
            'gitee_login'
        ];
        $sysConfigByGuestList = $this->dao->getSysConfigAll($fields);

        $sysConfigByGuestList['sys_logo'] = request()->domain() . $sysConfigByGuestList['sys_logo'];

        return success($sysConfigByGuestList);
    }

    /**
     * 读取系统配置
     * @param string|null $groupName 配置组名
     * @param array|null $keys 配置键名
     */
    public function listSystemConfig(?string $groupName, ?array $keys, $admin = 0)
    {
        $where = [];
        if (!empty($groupName)) {
            $where[] = ['group_name', '=', $groupName];
        }
        if (!empty($keys)) {
            $where[] = ['key', 'in', $keys];
        }
        $result = $this->dao->getColumn($where, 'value', 'key');

        return $admin == 1 ? success($result) : amis_success($result);
    }

    /**
     * 保存系统配置
     */
    public function editSystemConfig(string $groupName, array $data)
    {
        foreach ($data as $k => $v) {
            if (in_array($k, AmisKeywordsEnum::KEYWORDS)) continue;

            $key = camel_to_snake($k);
            $this->dao->saveSystemConfig($groupName, $key, $v);
        }

        return amis_success();
    }
}